package com.putao.album.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.putao.album.ahibernate.table.TableUtils;
import com.putao.album.application.GlobalApplication;
import com.putao.album.db.tables.InMessage;
import com.putao.album.util.AppHelper;
import com.putao.album.util.Loger;

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "album.db";


//----如果你使用的是将数据库的文件创建在SD卡中，那么创建数据库mysql如下操作：
//       mysql = SQLiteDatabase.openOrCreateDatabase(file, null);
//--- 如果想把数据库文件默认放在系统中,那么创建数据库mysql如下操作：
//       mysql = myOpenHelper.getWritableDatabase(); // 实例数据库

    static DatabaseHelper mInstance;

    public synchronized static DatabaseHelper getInstance() {
        if (mInstance == null) {
            mInstance = new DatabaseHelper(GlobalApplication.getInstance());
        }
        return mInstance;
    }

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, AppHelper.getVersionCode());
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Loger.d("create tables");
        try {
//            Loger.d("create table message...");
            TableUtils.createTable(db, true, InMessage.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        Loger.d("onUpgrade...." + "old:" + oldVersion + ",new:" + newVersion);
        switch (newVersion) {
            case 2:
                doUpgradeTableMessage(db, oldVersion);
                break;
        }
    }

    /**
     * 升级消息表
     */
    void doUpgradeTableMessage(SQLiteDatabase db, int oldVersion) {
        if (oldVersion >= 2) {
            return;
        }
        String tableName = TableUtils.getTableName(InMessage.class);
        String[] columns = getColumnNames(db, tableName);
        StringBuilder sb_columns = new StringBuilder();
        if (columns != null) {
            for (int i = 0; i < columns.length; i++) {
                sb_columns.append(columns[i]);
                if (i < columns.length - 1) {
                    sb_columns.append(",");
                }
            }
            upgradeTables(db, tableName, sb_columns.toString());
        }
    }

    /**
     * 根据表名获取表列
     *
     * @param db
     * @param tableName
     * @return
     */
    protected String[] getColumnNames(SQLiteDatabase db, String tableName) {
        String[] columnNames = null;
        Cursor c = null;

        try {
            c = db.rawQuery("PRAGMA table_info(" + tableName + ")", null);
            if (null != c) {
                int columnIndex = c.getColumnIndex("name");
                if (-1 == columnIndex) {
                    return null;
                }

                int index = 0;
                columnNames = new String[c.getCount()];
                for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                    columnNames[index] = c.getString(columnIndex);
                    index++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            c.close();
        }

        return columnNames;
    }


    /**
     * Upgrade tables. In this method, the sequence is:
     * <b>
     * <p>[1] Rename the specified table as a temporary table.
     * <p>[2] Create a new table which name is the specified name.
     * <p>[3] Insert data into the new created table, data from the temporary table.
     * <p>[4] Drop the temporary table.
     * </b>
     *
     * @param db        The database.
     * @param tableName The table name.
     * @param columns   The columns range, format is "ColA, ColB, ColC, ... ColN";
     */
    protected void upgradeTables(SQLiteDatabase db, String tableName, String columns) {
        try {
            db.beginTransaction();

            // 1, Rename table.

            String tempTableName = tableName + "_temp";
            String sql = "ALTER TABLE " + tableName + " RENAME TO " + tempTableName;
//            Loger.d("Rename table:" + sql);
            db.execSQL(sql);

            // 2, Create table.
//            Loger.d("ReCreate table");
            TableUtils.createTable(db, true, InMessage.class);

            // 3, Load data

            sql = "INSERT INTO " + tableName + " (" + columns + ") " + " SELECT " + columns + " FROM " + tempTableName;
//            Loger.d("Load data:" + sql);
            db.execSQL(sql);

//             4, Drop the temporary table.
            db.execSQL("DROP TABLE IF EXISTS " + tempTableName, null);

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }
}
